import request from '@/utils/request';

// API 基础 URL
const BASE_AI_URL = 'https://open.bigmodel.cn/api/paas/v4';
const BASE_URL= '';

// 创建一个函数来获取当前的 API 密钥
const getApiKey = () => {
  return 'd4e96ed1d3a66152c1c213c4ead295bd.Jnq8Xqo2Z6hN65DR';
};

// AI 助手相关 API
const aiAssistantApi = {
  sendMessage: (data) => {
    const headers = {
      'Authorization': `Bearer ${getApiKey()}`,
      'Content-Type': 'application/json'
    };
    return request.post(`${BASE_AI_URL}/chat/completions`, data, { headers });
  },
  streamMessage: (data, onChunk) => {
    const headers = {
      'Authorization': `Bearer ${getApiKey()}`,
      'Content-Type': 'application/json'
    };
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${BASE_AI_URL}/chat/completions`, true);
      xhr.setRequestHeader('Authorization', headers.Authorization);
      xhr.setRequestHeader('Content-Type', headers['Content-Type']);
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 3) {
          // 新数据可用
          const newData = xhr.responseText.substr(xhr.seenBytes || 0);
          xhr.seenBytes = xhr.responseText.length;
          const lines = newData.split('\n');
          lines.forEach(line => {
            if (line.startsWith('data: ')) {
              const jsonData = line.slice(5);
              if (jsonData.trim() === '[DONE]') {
                resolve();
              } else {
                onChunk(jsonData);
              }
            }
          });
        } else if (xhr.readyState === 4) {
          // 请求完成
          if (xhr.status === 200) {
            resolve();
          } else {
            reject(new Error(`HTTP error! status: ${xhr.status}`));
          }
        }
      };
      xhr.send(JSON.stringify(data));
    });
  },
};

export default {
  ai: aiAssistantApi,
};